<template>
  <div class="weather-container">
    <!-- 头部控制区域 -->
    <div class="weather-header">
      <div class="location-controls">
        <div class="search-section">
            <el-input v-model="searchCity" placeholder="输入城市名称 (如: 北京, 上海)" class="city-input"
              @keyup.enter="searchByCity">
            <template #append>
              <el-button @click="searchByCity" :loading="loading">
                <el-icon>
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </div>

        <div class="coordinate-section">
          <el-input-number v-model="latitude" :min="-90" :max="90" :precision="4" placeholder="纬度"
            class="coordinate-input" />
          <el-input-number v-model="longitude" :min="-180" :max="180" :precision="4" placeholder="经度"
            class="coordinate-input" />
          <el-button @click="searchByCoordinates" :loading="loading">
            按坐标查询
          </el-button>
        </div>
      </div>

      
    </div>

    <!-- 天气信息显示区域 -->
    <div class="weather-content" v-if="weatherData">
      <el-card class="weather-card">
        <template #header>
          <div class="card-header">
            <span class="location-info">
              <el-icon>
                <Location />
              </el-icon>
              {{ locationInfo }}
            </span>
            <span class="update-time">
              <el-icon>
                <Clock />
              </el-icon>
              {{ updateTime }}
            </span>
          </div>
        </template>

        <!-- 天气预警 -->
        <div class="weather-alerts" v-if="weatherAlerts.length > 0">
          <h3 class="alerts-title">
            <el-icon>
              <Warning />
            </el-icon>
            天气预警
          </h3>
          <div class="alerts-list">
            <div 
              v-for="(alert, index) in weatherAlerts" 
              :key="index" 
              class="alert-item"
              :class="`alert-${alert.level}`"
            >
              <div class="alert-icon">
                <el-icon>
                  <Warning />
                </el-icon>
              </div>
              <div class="alert-content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="alert-description">{{ alert.description }}</div>
                <div class="alert-time">{{ alert.time }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 当前天气 -->
        <div class="current-weather" v-if="currentWeather">
          <div class="weather-main">
            <div class="temperature">
              <span class="temp-value">{{ currentWeather.temperature }}</span>
              <span class="temp-unit">°C</span>
            </div>
              <div class="weather-desc">
                <span class="weather-text">{{ currentWeather.description }}</span>
              </div>
              
              <div class="day-rainfall">
                <span class="rainfall-text">降雨: {{ currentWeather.rainfall  }}mm</span>
              </div>
          </div>

          <div class="weather-details">
            <div class="detail-item">
              <el-icon>
                <Sunny />
              </el-icon>
              <span>湿度: {{ currentWeather.humidity }}%</span>
            </div>
            <div class="detail-item">
              <el-icon>
                <WindPower />
              </el-icon>
              <span>风速: {{ currentWeather.windSpeed }} m/s</span>
            </div>
            <div class="detail-item">
              <el-icon>
                <Compass />
              </el-icon>
              <span>风向: {{ currentWeather.windDirection }}</span>
            </div>
            <div class="detail-item">
              <el-icon>
                <View />
              </el-icon>
              <span>能见度: {{ currentWeather.visibility }} km</span>
            </div>
            <div class="detail-item">
              <el-icon>
                <Cloudy />
              </el-icon>
              <span>云量: {{ currentWeather.cloudiness }}%</span>
            </div>
            <div class="detail-item">
              <el-icon>
                <TrendCharts />
              </el-icon>
              <span>气压: {{ currentWeather.pressure }} hPa</span>
            </div>
          </div>
        </div>

        <!-- 7天预报预警 -->
        <div class="forecast-alerts" v-if="forecastAlerts.length > 0">
          <h3 class="forecast-alerts-title">
            <el-icon>
              <Warning />
            </el-icon>
            未来7天预警
          </h3>
          <div class="forecast-alerts-list">
            <div 
              v-for="(alert, index) in forecastAlerts" 
              :key="index" 
              class="forecast-alert-item"
              :class="`alert-${alert.level}`"
            >
              <div class="forecast-alert-icon">
                <el-icon>
                  <Warning />
                </el-icon>
              </div>
              <div class="forecast-alert-content">
                <div class="forecast-alert-title">{{ alert.title }}</div>
                <div class="forecast-alert-description">{{ alert.description }}</div>
                <div class="forecast-alert-time">{{ alert.time }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 7天预报 -->
        <div class="forecast-section">
          <h3 class="section-title">
            <el-icon>
              <Calendar />
            </el-icon>
            未来7天预报
          </h3>
          <div class="forecast-list">
            <div v-for="(day, index) in forecastDays" :key="index" class="forecast-day">
              <div class="day-rainfall">
                <span class="rainfall-text">降雨: {{ day.rainfall }}mm</span>
              </div>
              
              <div class="day-header">
                <span class="day-date">{{ day.date }}</span>
                <span class="day-week">{{ day.weekday }}</span>
              </div>
              <div class="day-weather">
                <span class="day-desc">{{ day.weather }}</span>
              </div>
               
              <div class="day-details">
                <div class="detail-row">
                  <span>湿度: {{ day.humidity }}%</span>
                  <span>风速: {{ day.windSpeed }} m/s</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-card>
        <div class="loading-content">
          <el-icon class="loading-icon">
            <Loading />
          </el-icon>
          <span>正在获取天气数据...</span>
        </div>
      </el-card>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-container">
      <el-card>
        <div class="error-content">
          <el-icon class="error-icon">
            <Warning />
          </el-icon>
          <span>{{ error }}</span>
          <el-button @click="retry" type="primary" size="small">重试</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search, Location, Clock, Sunny, WindPower,
  Compass, View, Cloudy, TrendCharts, Calendar,
  Loading, Warning
} from '@element-plus/icons-vue'
import WeatherService, { type WeatherResponse, type CityInfo } from '../api/weather'

// 天气预警类型定义
interface WeatherAlert {
  level: 'low' | 'medium' | 'high' | 'severe'
  title: string
  description: string
  time: string
  type: 'rain' | 'wind' | 'temperature' | 'visibility' | 'storm'
}

// 响应式数据
const loading = ref(false)
const error = ref('')
const weatherData = ref<WeatherResponse | null>(null)
const commonCities = ref<CityInfo[]>([])
const searchCity = ref('')
const latitude = ref(39.9042) // 北京纬度
const longitude = ref(116.4074) // 北京经度
const weatherAlerts = ref<WeatherAlert[]>([])
const forecastAlerts = ref<WeatherAlert[]>([])

// 计算属性
const locationInfo = computed(() => {
  if (!weatherData.value) return ''

  if (weatherData.value.coordinates) {
    return `坐标: ${weatherData.value.coordinates.latitude.toFixed(4)}°N, ${weatherData.value.coordinates.longitude.toFixed(4)}°E`
  } else if (weatherData.value.cityName) {
    return `城市: ${weatherData.value.cityName}`
  }
  return '未知位置'
})

const updateTime = computed(() => {
  if (!weatherData.value?.timestamp) return ''
  return new Date(weatherData.value.timestamp).toLocaleString('zh-CN')
})

const currentWeather = computed(() => {
  if (!weatherData.value?.data) return null

  // 解析天气数据字符串
  const data = weatherData.value.data
  const lines = data.split('\n')

  // 提取当前天气信息
  const currentWeatherInfo: any = {}

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()

    if ((line.includes('温度：') || line.includes('温度:')) && !currentWeatherInfo.temperature) {
      const tempValue = line.split(/[：:]/)[1].replace('°C', '').trim()
      currentWeatherInfo.temperature = tempValue
    } else if ((line.includes('体感温度：') || line.includes('体感温度:')) && currentWeatherInfo.temperature) {
      const feelsLikeValue = line.split(/[：:]/)[1].replace('°C', '').trim()
      currentWeatherInfo.feelsLike = feelsLikeValue
    } else if (line.includes('天气：')) {
      currentWeatherInfo.description = line.split('：')[1]
    } else if (line.includes('湿度：')) {
      currentWeatherInfo.humidity = line.split('：')[1].replace('%', '')
    } else if (line.includes('风速：')) {
      currentWeatherInfo.windSpeed = line.split('：')[1].replace(' m/s', '')
    } else if (line.includes('风向：')) {
      currentWeatherInfo.windDirection = line.split('：')[1]
    } else if (line.includes('能见度：')) {
      currentWeatherInfo.visibility = line.split('：')[1].replace(' km', '')
    } else if (line.includes('云量：')) {
      currentWeatherInfo.cloudiness = line.split('：')[1].replace('%', '')
    } else if (line.includes('气压：')) {
      currentWeatherInfo.pressure = line.split('：')[1].replace(' hPa', '')
    } else if (line.includes('降雨量：')) {
      const rainfallValue = line.split('：')[1].trim()
      currentWeatherInfo.rainfall = rainfallValue === '无降雨' ? 0 : parseFloat(rainfallValue.replace(' mm', ''))
    }
  }

  return currentWeatherInfo
})

const forecastDays = computed(() => {
  if (!weatherData.value?.data) return []

  const data = weatherData.value.data
  const lines = data.split('\n')
  const days: any[] = []

  console.log('7天预报解析开始，总行数:', lines.length)

  let inForecastSection = false
  let currentDay: any = null

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim()

    if (line.includes('未来7天预报：')) {
      inForecastSection = true
      continue
    }

    if (inForecastSection && line.includes('：')) {
      // 解析日期行
      const dateMatch = line.match(/(\d{4}-\d{2}-\d{2})\s+(.+?)：/)
      if (dateMatch) {
        if (currentDay) {
          days.push(currentDay)
        }
        currentDay = {
          date: dateMatch[1],
          weekday: dateMatch[2],
          weather: '',
          maxTemp: '',

          humidity: '',
          windSpeed: '',
          rainfall: 0
        }
      }
    }

    if (currentDay && inForecastSection) {
      if (line.includes('温度:')) {

        currentDay.maxTemp = line.split(':')[1].replace('°C', '').trim()

      } else if (line.includes('湿度：')) {
        currentDay.humidity = line.split('：')[1].replace('%', '')
      } else if (line.includes('风速：')) {
        currentDay.windSpeed = line.split('：')[1].replace(' m/s', '')
      } else if (line.includes('降雨：')) {
        const rainMatch = line.match(/降雨：(.+?) mm/)
        if (rainMatch) {
          currentDay.rainfall = parseFloat(rainMatch[1])
        }
      } else if (line.includes('天气：')) {
        currentDay.weather = line.split('：')[1]
      }
    }
  }

  if (currentDay) {
    days.push(currentDay)
  }

  return days.slice(0, 7) // 只显示7天
})

// 方法
const searchByCity = async () => {
  if (!searchCity.value.trim()) {
    ElMessage.warning('请输入城市名称')
    return
  }

  loading.value = true
  error.value = ''

  try {
    console.log('正在查询城市:', searchCity.value.trim())
    weatherData.value = await WeatherService.getForecastByCity(searchCity.value.trim())
    console.log('城市天气数据获取成功:', weatherData.value)
    ElMessage.success('获取天气数据成功')
    
    // 检测天气预警
    await nextTick()
    checkWeatherAlerts()
    checkForecastAlerts()
  } catch (err: any) {
    console.error('城市天气数据获取失败:', err)
    error.value = err.response?.data?.message || err.message || '获取天气数据失败'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

const searchByCoordinates = async () => {
  loading.value = true
  error.value = ''

  try {
    weatherData.value = await WeatherService.getForecastByCoordinates(latitude.value, longitude.value)
    ElMessage.success('获取天气数据成功')
    
    // 检测天气预警
    await nextTick()
    checkWeatherAlerts()
    checkForecastAlerts()
  } catch (err: any) {
    error.value = err.response?.data?.message || '获取天气数据失败'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

const selectCity = (cityName: string) => {
  searchCity.value = cityName
  searchByCity()
}

const retry = () => {
  if (searchCity.value) {
    searchByCity()
  } else {
    searchByCoordinates()
  }
}

// 天气预警检测
const checkWeatherAlerts = () => {
  if (!currentWeather.value) return

  const alerts: WeatherAlert[] = []
  const now = new Date()

  // 调试信息
  console.log('当前天气数据:', currentWeather.value)
  console.log('温度值:', currentWeather.value.temperature)

  // 温度预警
  const temperature = parseFloat(currentWeather.value.temperature)
  console.log('解析后的温度:', temperature)
  if (temperature >= 35) {
    alerts.push({
      level: 'high',
      title: '高温预警',
      description: `当前温度${temperature}°C，请注意防暑降温，避免长时间户外活动`,
      time: now.toLocaleString('zh-CN'),
      type: 'temperature'
    })
  } else if (temperature <= -10) {
    alerts.push({
      level: 'high',
      title: '低温预警',
      description: `当前温度${temperature}°C，请注意保暖，避免冻伤`,
      time: now.toLocaleString('zh-CN'),
      type: 'temperature'
    })
  }

  // 降雨预警
  const rainfall = currentWeather.value.rainfall
  console.log('降雨量:', rainfall)
  if (rainfall > 50) {
    alerts.push({
      level: 'severe',
      title: '暴雨预警',
      description: `降雨量${rainfall}mm，请注意防范洪涝灾害，避免涉水出行`,
      time: now.toLocaleString('zh-CN'),
      type: 'rain'
    })
  } else if (rainfall > 25) {
    alerts.push({
      level: 'high',
      title: '大雨预警',
      description: `降雨量${rainfall}mm，请注意出行安全，携带雨具`,
      time: now.toLocaleString('zh-CN'),
      type: 'rain'
    })
  } else if (rainfall > 10) {
    alerts.push({
      level: 'medium',
      title: '中雨预警',
      description: `降雨量${rainfall}mm，建议携带雨具`,
      time: now.toLocaleString('zh-CN'),
      type: 'rain'
    })
  } else if (rainfall > 0) {
    alerts.push({
      level: 'low',
      title: '小雨提醒',
      description: `降雨量${rainfall}mm，建议携带雨具`,
      time: now.toLocaleString('zh-CN'),
      type: 'rain'
    })
  }

  // 风速预警
  const windSpeed = parseFloat(currentWeather.value.windSpeed)
  console.log('风速:', windSpeed)
  if (windSpeed >= 20) {
    alerts.push({
      level: 'severe',
      title: '大风预警',
      description: `风速${windSpeed}m/s，请注意防范高空坠物，避免户外活动`,
      time: now.toLocaleString('zh-CN'),
      type: 'wind'
    })
  } else if (windSpeed >= 15) {
    alerts.push({
      level: 'high',
      title: '强风预警',
      description: `风速${windSpeed}m/s，请注意出行安全`,
      time: now.toLocaleString('zh-CN'),
      type: 'wind'
    })
  } else if (windSpeed >= 10) {
    alerts.push({
      level: 'medium',
      title: '风力提醒',
      description: `风速${windSpeed}m/s，风力较大，注意安全`,
      time: now.toLocaleString('zh-CN'),
      type: 'wind'
    })
  }

  // 能见度预警
  const visibility = parseFloat(currentWeather.value.visibility)
  console.log('能见度:', visibility)
  if (visibility < 1) {
    alerts.push({
      level: 'severe',
      title: '大雾预警',
      description: `能见度${visibility}km，请注意交通安全，谨慎驾驶`,
      time: now.toLocaleString('zh-CN'),
      type: 'visibility'
    })
  } else if (visibility < 3) {
    alerts.push({
      level: 'high',
      title: '雾霾预警',
      description: `能见度${visibility}km，建议减少户外活动`,
      time: now.toLocaleString('zh-CN'),
      type: 'visibility'
    })
  } else if (visibility < 5) {
    alerts.push({
      level: 'medium',
      title: '能见度提醒',
      description: `能见度${visibility}km，能见度较低，注意安全`,
      time: now.toLocaleString('zh-CN'),
      type: 'visibility'
    })
  }

  // 综合天气预警
  const description = currentWeather.value.description.toLowerCase()
  console.log('天气描述:', description)
  
  if (description.includes('雷') || description.includes('暴')) {
    alerts.push({
      level: 'severe',
      title: '雷暴预警',
      description: '检测到雷暴天气，请避免户外活动，注意防雷安全',
      time: now.toLocaleString('zh-CN'),
      type: 'storm'
    })
  }
  
  // 雪天预警
  if (description.includes('雪')) {
    alerts.push({
      level: 'high',
      title: '雪天预警',
      description: '检测到雪天，请注意路面湿滑，谨慎驾驶',
      time: now.toLocaleString('zh-CN'),
      type: 'storm'
    })
  }
  
  // 冰雹预警
  if (description.includes('雹')) {
    alerts.push({
      level: 'severe',
      title: '冰雹预警',
      description: '检测到冰雹天气，请避免户外活动，注意安全',
      time: now.toLocaleString('zh-CN'),
      type: 'storm'
    })
  }
  
  // 沙尘暴预警
  if (description.includes('沙') || description.includes('尘')) {
    alerts.push({
      level: 'high',
      title: '沙尘预警',
      description: '检测到沙尘天气，建议减少户外活动，佩戴口罩',
      time: now.toLocaleString('zh-CN'),
      type: 'visibility'
    })
  }
  
  // 湿度预警
  const humidity = parseFloat(currentWeather.value.humidity)
  console.log('湿度:', humidity)
  if (humidity >= 90) {
    alerts.push({
      level: 'medium',
      title: '高湿度提醒',
      description: `湿度${humidity}%，湿度很高，注意防潮`,
      time: now.toLocaleString('zh-CN'),
      type: 'temperature'
    })
  } else if (humidity <= 20) {
    alerts.push({
      level: 'medium',
      title: '低湿度提醒',
      description: `湿度${humidity}%，空气干燥，注意保湿`,
      time: now.toLocaleString('zh-CN'),
      type: 'temperature'
    })
  }

  weatherAlerts.value = alerts

  // 显示预警通知
  if (alerts.length > 0) {
    const severeAlerts = alerts.filter(alert => alert.level === 'severe')
    const highAlerts = alerts.filter(alert => alert.level === 'high')
    
    if (severeAlerts.length > 0) {
      ElMessage({
        message: `⚠️ 严重天气预警：${severeAlerts[0].title}`,
        type: 'error',
        duration: 8000,
        showClose: true
      })
    } else if (highAlerts.length > 0) {
      ElMessage({
        message: `⚠️ 天气预警：${highAlerts[0].title}`,
        type: 'warning',
        duration: 6000,
        showClose: true
      })
    }
  }
}

// 未来7天预警检测
const checkForecastAlerts = () => {
  if (!forecastDays.value || forecastDays.value.length === 0) return

  const alerts: WeatherAlert[] = []
  const now = new Date()

  console.log('开始检测7天预报预警，预报天数:', forecastDays.value.length)

  forecastDays.value.forEach((day, index) => {
    console.log(`检测第${index + 1}天预报:`, day)

    // 温度预警
    const temperature = parseFloat(day.maxTemp)
    if (!isNaN(temperature)) {
      if (temperature >= 35) {
        alerts.push({
          level: 'high',
          title: `${day.date} 高温预警`,
          description: `${day.date} 预计最高温度${temperature}°C，请注意防暑降温`,
          time: now.toLocaleString('zh-CN'),
          type: 'temperature'
        })
      } else if (temperature <= -10) {
        alerts.push({
          level: 'high',
          title: `${day.date} 低温预警`,
          description: `${day.date} 预计最高温度${temperature}°C，请注意保暖`,
          time: now.toLocaleString('zh-CN'),
          type: 'temperature'
        })
      }
    }

    // 降雨预警
    const rainfall = day.rainfall
    if (rainfall > 50) {
      alerts.push({
        level: 'severe',
        title: `${day.date} 暴雨预警`,
        description: `${day.date} 预计降雨量${rainfall}mm，请注意防范洪涝灾害`,
        time: now.toLocaleString('zh-CN'),
        type: 'rain'
      })
    } else if (rainfall > 25) {
      alerts.push({
        level: 'high',
        title: `${day.date} 大雨预警`,
        description: `${day.date} 预计降雨量${rainfall}mm，请注意出行安全`,
        time: now.toLocaleString('zh-CN'),
        type: 'rain'
      })
    } else if (rainfall > 10) {
      alerts.push({
        level: 'medium',
        title: `${day.date} 中雨预警`,
        description: `${day.date} 预计降雨量${rainfall}mm，建议携带雨具`,
        time: now.toLocaleString('zh-CN'),
        type: 'rain'
      })
    } else if (rainfall > 0) {
      alerts.push({
        level: 'low',
        title: `${day.date} 小雨提醒`,
        description: `${day.date} 预计降雨量${rainfall}mm，建议携带雨具`,
        time: now.toLocaleString('zh-CN'),
        type: 'rain'
      })
    }

    // 风速预警
    const windSpeed = parseFloat(day.windSpeed)
    if (!isNaN(windSpeed)) {
      if (windSpeed >= 20) {
        alerts.push({
          level: 'severe',
          title: `${day.date} 大风预警`,
          description: `${day.date} 预计风速${windSpeed}m/s，请注意防范高空坠物`,
          time: now.toLocaleString('zh-CN'),
          type: 'wind'
        })
      } else if (windSpeed >= 15) {
        alerts.push({
          level: 'high',
          title: `${day.date} 强风预警`,
          description: `${day.date} 预计风速${windSpeed}m/s，请注意出行安全`,
          time: now.toLocaleString('zh-CN'),
          type: 'wind'
        })
      } else if (windSpeed >= 10) {
        alerts.push({
          level: 'medium',
          title: `${day.date} 风力提醒`,
          description: `${day.date} 预计风速${windSpeed}m/s，风力较大`,
          time: now.toLocaleString('zh-CN'),
          type: 'wind'
        })
      }
    }

    // 天气描述预警
    const weatherDesc = day.weather.toLowerCase()
    if (weatherDesc.includes('雷') || weatherDesc.includes('暴')) {
      alerts.push({
        level: 'severe',
        title: `${day.date} 雷暴预警`,
        description: `${day.date} 预计有雷暴天气，请避免户外活动`,
        time: now.toLocaleString('zh-CN'),
        type: 'storm'
      })
    }
    
    if (weatherDesc.includes('雪')) {
      alerts.push({
        level: 'high',
        title: `${day.date} 雪天预警`,
        description: `${day.date} 预计有雪，请注意路面湿滑`,
        time: now.toLocaleString('zh-CN'),
        type: 'storm'
      })
    }
    
    if (weatherDesc.includes('雹')) {
      alerts.push({
        level: 'severe',
        title: `${day.date} 冰雹预警`,
        description: `${day.date} 预计有冰雹，请避免户外活动`,
        time: now.toLocaleString('zh-CN'),
        type: 'storm'
      })
    }
    
    if (weatherDesc.includes('沙') || weatherDesc.includes('尘')) {
      alerts.push({
        level: 'high',
        title: `${day.date} 沙尘预警`,
        description: `${day.date} 预计有沙尘天气，建议减少户外活动`,
        time: now.toLocaleString('zh-CN'),
        type: 'visibility'
      })
    }
  })

  forecastAlerts.value = alerts
  console.log('7天预报预警检测完成，预警数量:', alerts.length)
}

const loadCommonCities = async () => {
  try {
    const response = await WeatherService.getCommonCities()
    commonCities.value = response.data
  } catch (err) {
    console.error('获取城市列表失败:', err)
    // 如果API失败，使用默认城市列表
    commonCities.value = [
      { code: 'beijing', name: '北京' },
      { code: 'shanghai', name: '上海' },
      { code: 'guangzhou', name: '广州' },
      { code: 'shenzhen', name: '深圳' },
      { code: 'hangzhou', name: '杭州' },
      { code: 'nanjing', name: '南京' },
      { code: 'chengdu', name: '成都' },
      { code: 'wuhan', name: '武汉' }
    ]
  }
}

// 生命周期
onMounted(async () => {
  await loadCommonCities()
  // 默认加载北京天气
  await searchByCoordinates()
})
</script>

<style scoped>
.weather-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.weather-header {
  margin-bottom: 20px;
}

.location-controls {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.search-section {
  flex: 1;
  min-width: 300px;
}

.city-input {
  width: 100%;
}

.coordinate-section {
  display: flex;
  gap: 10px;
  align-items: center;
}

.coordinate-input {
  width: 120px;
}

.quick-cities {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.weather-content {
  margin-bottom: 20px;
}

.weather-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.location-info,
.update-time {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #666;
}

/* 天气预警样式 */
.weather-alerts {
  margin-bottom: 20px;
  padding: 15px;
  background: linear-gradient(135deg, #fff5f5, #fef0f0);
  border-radius: 12px;
  border-left: 4px solid #f56c6c;
}

.alerts-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

.alerts-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.alert-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.alert-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.alert-low {
  background: #f0f9ff;
  border-left: 3px solid #409eff;
}

.alert-medium {
  background: #fef7e0;
  border-left: 3px solid #e6a23c;
}

.alert-high {
  background: #fef0f0;
  border-left: 3px solid #f56c6c;
}

.alert-severe {
  background: #fef0f0;
  border-left: 3px solid #f56c6c;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.8; }
}

.alert-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.alert-low .alert-icon {
  color: #409eff;
}

.alert-medium .alert-icon {
  color: #e6a23c;
}

.alert-high .alert-icon,
.alert-severe .alert-icon {
  color: #f56c6c;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 4px;
}

.alert-low .alert-title {
  color: #409eff;
}

.alert-medium .alert-title {
  color: #e6a23c;
}

.alert-high .alert-title,
.alert-severe .alert-title {
  color: #f56c6c;
}

.alert-description {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 4px;
}

.alert-time {
  font-size: 12px;
  color: #999;
}

/* 7天预报预警样式 */
.forecast-alerts {
  margin-bottom: 20px;
  padding: 15px;
  background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
  border-radius: 12px;
  border-left: 4px solid #409eff;
}

.forecast-alerts-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
}

.forecast-alerts-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.forecast-alert-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.forecast-alert-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.forecast-alert-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.forecast-alert-content {
  flex: 1;
}

.forecast-alert-title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 4px;
}

.forecast-alert-description {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 4px;
}

.forecast-alert-time {
  font-size: 12px;
  color: #999;
}

.current-weather {
  margin-bottom: 30px;
}

.weather-main {
  display: flex;
  align-items: center;
  gap: 30px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.temperature {
  display: flex;
  align-items: baseline;
  gap: 5px;
}

.temp-value {
  font-size: 48px;
  font-weight: bold;
  color: #409eff;
}

.temp-unit {
  font-size: 24px;
  color: #666;
}

.weather-desc {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.weather-text {
  font-size: 18px;
  font-weight: 500;
}

.feels-like {
  font-size: 14px;
  color: #666;
}

.weather-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  font-size: 14px;
}

.forecast-section {
  margin-top: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.forecast-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 15px;
}

.forecast-day {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.forecast-day:hover {
  background: #f0f9ff;
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.day-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.day-date {
  font-weight: 600;
  color: #333;
}

.day-week {
  font-size: 12px;
  color: #666;
}

.day-weather {
  margin-bottom: 10px;
}

.day-desc {
  font-size: 14px;
  color: #666;
}

.day-rainfall {
  margin-bottom: 15px;
  padding: 10px 15px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.rainfall-text {
  font-size: 14px;
  font-weight: 600;
  color: white;
}

.day-temps {
  margin-bottom: 10px;
}

.temp-value {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.day-details {
  font-size: 12px;
  color: #666;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}

.loading-content,
.error-content {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 20px;
}

.loading-icon {
  font-size: 24px;
  color: #409eff;
  animation: spin 1s linear infinite;
}

.error-icon {
  font-size: 24px;
  color: #f56c6c;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .weather-container {
    padding: 10px;
  }

  .location-controls {
    flex-direction: column;
  }

  .coordinate-section {
    flex-direction: column;
    align-items: stretch;
  }

  .coordinate-input {
    width: 100%;
  }

  .weather-main {
    flex-direction: column;
    align-items: flex-start;
  }

  .weather-details {
    grid-template-columns: 1fr;
  }

  .forecast-list {
    grid-template-columns: 1fr;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .weather-alerts {
    padding: 10px;
  }

  .alert-item {
    padding: 10px;
  }

  .alert-title {
    font-size: 13px;
  }

  .alert-description {
    font-size: 12px;
  }

  .forecast-alerts {
    padding: 10px;
  }

  .forecast-alert-item {
    padding: 10px;
  }

  .forecast-alert-title {
    font-size: 13px;
  }

  .forecast-alert-description {
    font-size: 12px;
  }
}
</style>
